import React, { useEffect, useState } from 'react';
import './User.less';
import { useStore } from '../stores/index';
import { myAxios } from '../axios';
import OrderTable from '../components/OrderTable.jsx';
import StudentInfo from '../components/StudentInfo.jsx';
import { useLocation } from 'react-router-dom';
const User = () => {
    const location = useLocation();

  useEffect(() => {
    // 如果有 scrollToBottom 标志，则滚动到底部
    if (location.state?.scrollToBottom) {
      setTimeout(() => {
        window.scrollTo({
          top: document.documentElement.scrollHeight,
          behavior: 'smooth'
        });
      }, 100); // 添加小延时确保内容已渲染
    }
  }, [location]);
    const store = useStore();
    const userdata = store.userdata;

    const { id, name, nickName, phone, address, isTeacher, reward } = userdata;

    // 订单列表
    const [orders, setOrders] = useState([]);
    // 获取订单列表
    const fetchOrders = async () => {
        if (!isTeacher) {
            const response = await myAxios.get('/order/byUser', {
                params: {
                    userId: id
                }
            });

            // console.log(response.data.data);
            setOrders(response.data.data);
        } else {
            const response = await myAxios.get('/order/byUser', {
                params: {
                    teacherId: id
                }
            });
            // console.log(response.data.data);
            setOrders(response.data.data);
        }
    };

    // 确认操作
    const handleConfirm = async (record) => {
        console.log('确认订单:', record);
        console.log(record.orderId);
        console.log(userdata.isTeacher);
        if (isTeacher) {
            console.log("老师确认订单");
            const response = await myAxios.post(`/order/teacherConfirm/${record.orderId}`);
            console.log(response.data.code);
            fetchOrders();
        } else {
            console.log("家长确认订单");
            const response = await myAxios.post(`/order/parentConfirm/${record.orderId}`);
            console.log(response.data.code);
            fetchOrders();
        }
    };

    // 取消操作
    const handleCancel = async(record) => {
        console.log('取消订单:', record);
        console.log("取消",record.orderId);
        const response = await myAxios.delete(`/order/del/${record.orderId}`);
        // console.log(response.data);
        fetchOrders();
    };


    //获取学生信息
    const fetchStudentInfo = async () => {
        const response = await myAxios.get('/stu/find');
        // console.log(response.data.data);

        // 确保 response.data.data 是数组，如果不是则初始化为空数组
        const data = Array.isArray(response.data.data) ? response.data.data : [];
        // 处理 birthdate 和 gender 字
        const processedStudents = data.map(student => {
            const genderMap = {
                'Female': '女',
                'Male': '男'
            };
            return {
                ...student,
                birthdate: student.birthdate.split('T')[0], // 提取日期部分
                gender: genderMap[student.gender] || student.gender // 转换性别字段
            };
        });
        // console.log(processedStudents);
        store.saveStudents(processedStudents);
    };

    // 组件加载时获取订单列表
    useEffect(() => {
        fetchOrders();
        if (isTeacher) {
            fetchTeacherInfo();
        }
        else fetchStudentInfo();
    }, []);


    // 获取老师信息
    const [teacherInfo, setTeacherInfo] = useState({});
    const fetchTeacherInfo = async () => {
        console.log("老师信息");
        const response = await myAxios.get('/teacher/' + id);
        console.log(response.data.data);
        setTeacherInfo(response.data.data);
    };
    let content;
    const info = (
        <>
            <h1>个人信息</h1>
            <div className="info">
                <ul className="account-info">
                    <li>
                        <label>用户名</label>:
                        <span>{name}</span>
                    </li>
                    <li>
                        <label>名称</label>:
                        <span>{nickName}</span>
                    </li>
                    <li>
                        <label>积分</label>:
                        <span>{reward}</span>
                    </li>
                    <li>
                        <label>身份</label>:
                        <span>{isTeacher ? '教师' : '家长'}</span>
                    </li>
                    <li>
                        <label>联系电话</label>:
                        <span>{phone}</span>
                    </li>
                    <li>
                        <label>地址</label>:
                        <span>{address}</span>
                    </li>
                </ul>
            </div>

            <h1>服务记录</h1>
            <div className="info">
                <OrderTable
                    orders={orders}
                    onConfirm={handleConfirm}
                    onCancel={handleCancel}
                />
            </div>
        </>
    );

    if (isTeacher) {
        content = <div className="user-shell">
            {info}
            <h1>政府认证信息</h1>
            <div className="info">
                <div className="teacher-info">
                    <div className="img-container">
                        <img src={teacherInfo.profilePicture} alt="头像" />
                    </div>
                    <h3>学历信息</h3>
                    <p>{teacherInfo.education}</p>
                    <h3>个人简介</h3>
                    <p>{teacherInfo.bio}</p>
                    <h3>教学或工作经验</h3>
                    <p>{teacherInfo.experience}</p>
                    <h3>获奖经历</h3>
                    <p>{teacherInfo.certificates}</p>
                </div>
            </div>
        </div>;
    } else {
        content = (
            <div className="user-shell">
                {info}
                <h1>学生信息</h1>
                <div className="info">
                  <StudentInfo fetchStudentInfo={fetchStudentInfo} />
                </div>
            </div>
        );
    }

    return content;
};

export default User;